<?php

namespace App\Http\Controllers\dashboard;

use App\Constant\Enum;
use App\Models\UserWithdraw;
use App\Services\Withdraw\UserWithdrawService;
use Illuminate\Http\Request;

class WithdrawController extends BaseController
{
    /**
     * 提现审核列表.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        $query = UserWithdraw::query()
            ->with([
                'user:id,uuid,nickname,status,registered_at',
                'operator:id,username,name'
            ])
            ->latest();
        $status = $request->get('status');
        $uuid = $request->get('uuid');
        if ($status) {
            $query->where('status', $status);
        }
        if ($uuid) {
            $query->whereHas('user', function ($query) use ($uuid) {
                $query->where('uuid', $uuid);
            });
        }
        $list = $query->paginate($this->getPerPage());

        return $this->success($this->paginated($list));
    }

    /**
     * 处理提现请求.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function audit(Request $request)
    {
        $input = $request->post();

        $withdrawId = $input['withdraw_id'] ?? 0;
        $action = $input['status'] ?? '';
        $remark = $input['remark'] ?? '';

        if (empty($withdrawId)) {
            return $this->error("提现审核记录必传");
        }

        if (!in_array($action, [
            Enum::WITHDRAW_STATUS_APPROVED,
            Enum::WITHDRAW_STATUS_REJECTED,
        ])) {
            return $this->error('审核状态无效');
        }

        $userWithdraw = UserWithdraw::query()->find($withdrawId);
        if (!$userWithdraw) {
            return $this->error('提现申请不存在');
        }


        $user = auth('dash')->user();
        try {
            if ($action == Enum::WITHDRAW_STATUS_APPROVED) {
                UserWithdrawService::approve($userWithdraw, $remark, $user->admin_id);
            } else {
                UserWithdrawService::reject($userWithdraw, $remark, $user->admin_id);
            }
            return $this->success('审核成功');
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}
